<template>
  <el-dialog v-model="model" @close="closedDialog">
    <el-form
      ref="operationFormRef"
      :model="form"
      :rules="rules"
      label-width="160px"
    >
      <el-form-item :label="$t('sysOperation.code')" prop="operationCode">
        <el-input
          v-model="form.operationCode"
          :placeholder="$t('sysOperation.codeRequired')"
          :disabled="(form as OperationUpdateReq).operationId ? true : false"
          clearable
        />
      </el-form-item>
      <el-form-item :label="$t('sysOperation.name')" prop="operationName">
        <el-input
          v-model="form.operationName"
          :placeholder="$t('sysOperation.nameRequired')"
          clearable
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="closedDialog">{{ $t("common.cancel") }}</el-button>
        <el-button type="primary" @click="submitForm">
          {{ $t("common.confirm") }}
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
import { ref, reactive, type PropType } from "vue";
import { useI18n } from "vue-i18n";
const { t } = useI18n();
import { type FormInstance, type FormRules, ElMessage } from "element-plus";
import type {
  OperationKey,
  OperationFormReq,
  OperationUpdateReq,
} from "@/api/system/operation/types";
import { operationApi } from "@/api/system/operation/index";
const props = defineProps({
  entityKey: {
    type: Object as PropType<OperationKey>,
    default: () => {},
  },
});
const model = defineModel<boolean>();
const operationFormRef = ref<FormInstance>();
let form = reactive<OperationFormReq>({
  requestId: Math.random() * 10 + "",
  updateMask: "operationCode,operationName",
});

const keys = Object.keys(props.entityKey);

const update = ref(keys.length >= 1);

if (update.value) {
  operationApi.findById(props.entityKey).then(({ data }) => {
    Object.assign(form, data);
  });
}

// 修改操作编码时，检查编码是否重复
const operateCodeValidate = (rule: any, value: any, callback: any) => {
  if (value === "") {
    callback(new Error(t("sysOperation.codeRequired")));
  } else {
    if (!(form as OperationUpdateReq).operationId) {
      operationApi.checkOperationApi(value).then(({ data }) => {
        if (data === true) {
          callback(new Error("该编码已存在"));
        } else {
          callback();
        }
      });
    } else {
      callback();
    }
  }
};

const rules = reactive<FormRules<OperationFormReq>>({
  operationCode: [
    {
      required: true,
      validator: operateCodeValidate,
      trigger: "blur",
    },
  ],
  operationName: [
    {
      required: true,
      message: t("sysOperation.nameRequired"),
      trigger: "blur",
    },
  ],
});
const emits = defineEmits(["refresh"]);
const submitForm = async () => {
  await operationFormRef.value?.validate((valid) => {
    if (valid) {
      if (update.value) {
        operationApi.update(form as OperationUpdateReq).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      } else {
        operationApi.create(form).then((response) => {
          if (response.status === 200) {
            ElMessage({
              message: t("common.submitSuccess"),
              type: "success",
            });
            if (model.value) {
              model.value = false;
            }
            emits("refresh", response.status === 200);
          }
        });
      }
    }
  });
};

// 关闭弹框
function closedDialog() {
  if (model.value) {
    model.value = false;
  }
}
</script>
